package com.chen.base.utils;

import lombok.SneakyThrows;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.Objects;

/**
 * 公共工具类
 * @author: ChenJinLong
 * @DATE: 2024/8/5
 **/
public class CommonUtil {

    /** bean转字符串且格式化 **/
    @SneakyThrows
    public static <T> String toStr(T t){
        StringBuilder builder = new StringBuilder(t.getClass().getSimpleName() + "(\n");
        Field[] fields = t.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            field.setAccessible(true);
            String name = field.getName();
            Object value = field.get(t);
            builder.append("\t").append(name).append(" = ").append(value);
            if (i != fields.length - 1){
                builder.append(",");
            }
            builder.append("\n");
        }

        builder.append(")");
        return builder.toString();
    }

    /** 请求 **/
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /** 响应 **/
    public static HttpServletResponse getResponse(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /** 获取主启动类Class **/
    @SneakyThrows
    public static Class<?> mainClass(){
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if ("main".equals(stackTraceElement.getMethodName())) {
                return Class.forName(stackTraceElement.getClassName());
            }
        }

        return null;
    }
}
